<template>
  <el-dialog v-model="visible" :append-to-body="true" width="750px" title="编辑客户信息">
    <el-form :model="formData" label-width="95px" size="small" :inline="false">
      <el-row style="margin-bottom: 18px">
        <el-col :span="12">
          <el-form-item label="客户全称" prop="intactName">
            <el-input v-model="formData.intactName" placeholder="请填写客户全称" maxlength="128" clearable/>
          </el-form-item>
          <el-form-item label="客户简称" prop="nickname">
            <el-input v-model="formData.nickname" placeholder="请填写客户简称" maxlength="16" clearable/>
          </el-form-item>
          <el-form-item label="客户类型" prop="customerType">
            <el-select v-model="formData.customerType" placeholder="请选择客户类型" size="small" style="width: 100%">
              <el-option label="代理商" :value="0"/>
              <el-option label="直客" :value="1"/>
              <el-option label="代理商客户" :value="2"/>
            </el-select>
          </el-form-item>
          <el-form-item label="外协公司" prop="outCompany">
            <el-input v-model="formData.outCompany" placeholder="请填写外协公司" maxlength="128" clearable/>
          </el-form-item>
          <el-form-item label="级别" prop="levelId">
            <el-select v-model="formData.levelId" placeholder="请选择客户级别" size="small" style="width: 230px">
              <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-icon :size="16" style="margin-left: 5px;cursor: pointer" color="var(--next-bg-topBarColor)" @click="levelVisible = true">
              <ele-Setting/>
            </el-icon>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分部" prop="branchName">
            <el-input v-model="formData.branchName" placeholder="请填写分部名称" maxlength="32" clearable/>
          </el-form-item>
          <el-form-item label="上级客户" prop="superiorId">
            <el-select v-model="formData.superiorId" placeholder="请选择上级客户" style="width: 100%" clearable filterable>
              <el-option v-for="item in customerList" :key="item.id" :label="item.nickname" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="客户分类" prop="type">
            <el-radio-group v-model="formData.type">
              <el-radio :label="0">组织</el-radio>
              <el-radio :label="1">个人</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="屏蔽状态">
            <el-radio-group v-model="formData.block">
              <el-radio :label="0">未屏蔽</el-radio>
              <el-radio :label="1">已屏蔽</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="经营范围" prop="businessScope">
            <el-select v-model="formData.businessScope" placeholder="请选择经营范围" style="width:230px">
              <el-option v-for="item in businessList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            <el-icon :size="16" title="快捷经营范围设置" style="margin-left:5px;cursor:pointer;" color="var(--next-bg-topBarColor)" @click="businessVisible = true">
              <ele-Setting/>
            </el-icon>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item prop="sourceChannel" label="客户来源" style="margin-top: 18px">
        <el-select v-model="formData.sourceChannel" placeholder="请选择渠道" size="small" @change="channelChange" clearable filterable style="width: 230px">
          <el-option v-for="item in sourceList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <el-select v-model="formData.sourceScene" :placeholder="formData.sourceChannel ? '请选择来源场景' : '请先选择来源渠道'" :disabled="!formData.sourceChannel" size="small" filterable clearable style="margin-left: 10px;width: 230px">
          <el-option v-for="item in sceneList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
        <el-icon :size="16" title="来源设置" style="margin-left:5px;cursor:pointer" color="var(--next-bg-topBarColor)" @click="sourceVisible = true">
          <ele-Setting/>
        </el-icon>
      </el-form-item>
      <el-form-item label="地点定位" prop="location">
        <el-cascader ref="areaTree" v-model="area" :options="cityList" :props="areaProps" style="width:89.8%" @change="areaChange"/>
        <el-input placeholder="请输入详细地址" v-model="formData.address" style="width:89.8%;margin-top:10px;height: auto" @blur="getMarker"/>
        <!--  地图  -->
        <div id="map" ref="map"></div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button size="small" @click="visible = false">取消</el-button>
      <el-button type="primary" size="small" :loading="submitLoading" @click="submit">提交</el-button>
    </template>

    <!--  客户经营范围设置   -->
    <business-setting v-model:dialog-visible="businessVisible" @callback="getBusinessData"/>
    <!--  客户来源设置  -->
    <source-setting v-model:dialog-visible="sourceVisible" @callback="getSourceData"/>
    <!-- 客户级别设置 -->
    <level-setting v-model:dialog-visible="levelVisible" @callback="getLevelData"/>
  </el-dialog>
</template>

<script>
import {computed, reactive, toRefs, shallowRef, getCurrentInstance} from 'vue'
import {city} from '/@/utils/city'
import {ElMessage} from 'element-plus'
import sourceApi from '/@/api/ums/customer/source'
import businessApi from '/@/api/ums/customer/business'
import levelApi from '/@/api/ums/customer/level'
import customerApi from '/@/api/ums/customer'
import AMapLoader from '@amap/amap-jsapi-loader'
import {changeDetSelect} from '/@/utils/utils'
import BusinessSetting from '/@/views/crm/components/BusinessSetting.vue'
import SourceSetting from '/@/views/crm/components/SourceSetting.vue'
import LevelSetting from '/@/views/crm/components/LevelSetting.vue'

export default {
  name: 'CustomerEdit',
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    defaultForm: {
      type: Object,
      default: {}
    }
  },
  components: {
    BusinessSetting,
    SourceSetting,
    LevelSetting
  },
  emits: ['update:defaultForm', 'update:dialogVisible'],
  setup(props, context) {
    const {proxy} = getCurrentInstance()
    let map = shallowRef(null)
    let marker = shallowRef(null)
    let geocoder = null
    let Map = null
    const {dialogVisible, defaultForm} = toRefs(props)
    let visible = computed({
      get: () => {
        if (dialogVisible.value) {
          state.formData = defaultForm
          if (state.formData.addrCode) {
            state.area = state.formData.addrCode.split(',')
            state.areaLabel = state.formData.addrName.split(',')
          }
          getSourceData(0)
          if (state.formData.sourceScene) {
            getSourceData(state.formData.sourceChannel)
          }
          getBusinessData()
          getLevelData()
          customerApi.getList().then(res => state.customerList = res.data).catch(e => console.log(e))
          setTimeout(() => initMap(), 100)
        }
        return dialogVisible.value
      },
      set: val => context.emit('update:dialogVisible', val)
    })

    const state = reactive({
      formData: {
        id: null,
        intactName: null,
        branchName: null,
        nickname: null,
        type: null,
        customerType: null,
        superiorId: null,
        businessScope: null,
        outCompany: null,
        address: null,  // 地址全称
        addrCode: null,   // 省市区地址编码, 逗号隔开
        addrName: null,   // 省市区地址, 逗号隔开
        lng: null,    // 经度
        lat: null,    // 纬度
        sourceChannel: null,
        sourceScene: null
      },
      submitLoading: false,
      area: [],
      cityList: city,
      areaProps: {
        expandTrigger: 'hover',
        value: 'code'
      },
      levelList: [],
      levelVisible: false,
      customerList: [],
      businessList: [],
      businessVisible: false,
      sourceList: [],
      sceneList: [],
      sourceVisible: false,
    })

    const getSourceData = (pid) => sourceApi.sourceSelector(pid).then(res => {
      if (pid) {
        state.sceneList = res.data
      } else {
        state.sourceList = res.data
      }
    }).catch(e => console.log(e))
    const getBusinessData = () => businessApi.businessSelector().then(res => state.businessList = res.data).catch(e => console.log(e))
    const getLevelData = () => levelApi.levelList().then(res => state.levelList = res.data).catch(e => console.log(e))
    const submit = () => {
      let params = JSON.parse(JSON.stringify(state.formData))
      params.id = params.customerId
      customerApi.edit(params).then(res => {
        if (res.data) {
          ElMessage.success('保存成功！')
          context.emit('update:defaultForm', res.data)
          context.emit('update:dialogVisible', false)
        }
      }).catch(e => console.log(e))
    }
    // 来源渠道改变
    const channelChange = (val) => {
      // 清空具体场景
      state.formData.sourceScene = null
      if (val) {
        // 加载二级来源数据
        sourceApi.sourceSelector(val).then(res => state.sceneList = res.data).catch(e => console.log(e))
      } else {
        state.sceneList = []
      }
    }
    const areaChange = (codes) => {
      state.areaLabel = proxy.$refs['areaTree'].getCheckedNodes()[0].pathLabels
      // 地图反解析赋值
      // state.formData.addrName = state.areaLabel + ''
      // state.formData.addrCode = codes + ''
    }
    const initMap = () => {
      AMapLoader.load({
        key: '54258384f8ac03ec2032977d0a45e678',             // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0',      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geolocation', 'AMap.LngLat', 'AMap.Marker', 'AMap.Pixel', 'AMap.Geocoder']       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      }).then((AMap) => {
        Map = AMap
        map = new AMap.Map('map', {  //设置地图容器id
          zoom: 16
        })
        let geolocation = new AMap.Geolocation({
          // 是否使用高精度定位，默认：true
          enableHighAccuracy: true,
          // 设置定位超时时间，默认：无穷大
          timeout: 10000
        })
        geolocation.getCityInfo((status, result) => {
          let lng = state.formData.lng || result.position[0]
          let lat = state.formData.lat || result.position[1]
          if (status == 'complete') {
            map.setCenter(new AMap.LngLat(lng, lat))
            marker = new AMap.Marker({
              icon: '/src/assets/position.png',
              position: [lng, lat],
              offset: new AMap.Pixel(-13, -30)
            })
            marker.setMap(map)
          } else {
            let lng = state.formData.lng || 113.295799
            let lat = state.formData.lat || 23.035493
            map.setCenter(new AMap.LngLat(lng, lat))
            marker = new AMap.Marker({
              icon: '/src/assets/position.png',
              position: [lng, lat],
              offset: new AMap.Pixel(-13, -30)
            })
            console.log('error => ', result)
          }
        })
        geocoder = new AMap.Geocoder()

        map.on('click', (result) => {
          const lng = result['lnglat'].getLng()
          const lat = result['lnglat'].getLat()
          state.formData.lng = lng
          state.formData.lat = lat
          // eslint-disable-next-line vue/no-ref-as-operand
          marker.setPosition(new AMap.LngLat(lng, lat))
          geocoder.getAddress([lng, lat], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              // console.log("地图回调数据=>", result);
              const addressComponent = result['regeocode']['addressComponent']
              const {district, city, province} = addressComponent
              const codeArray = changeDetSelect(addressComponent.adcode, state.cityList, 'code')
              state.area = codeArray
              //    省/市/区(县)
              state.areaLabel = [province, city, district]
              state.formData.addrName = state.areaLabel + ''
              state.formData.addrCode = codeArray[0] + ',' + codeArray[1] + ',' + codeArray[2]
              // 地址全称
              state.formData.address = result['regeocode']['formattedAddress']
            }
          })
        })
      }).catch(e => console.log(e))
    }
    const getMarker = () => {
      let addr = state.areaLabel.join('')
      if (state.formData.address.indexOf(addr) < 0) {
        addr += state.formData.address
      } else {
        addr = state.formData.address
      }
      geocoder.getLocation(addr, function (status, result) {
        if (status === 'complete' && result.info === 'OK') {
          map.setCenter(new Map.LngLat(result['geocodes'][0].location.lng, result['geocodes'][0].location.lat))
          marker.setPosition(new Map.LngLat(result['geocodes'][0].location.lng, result['geocodes'][0].location.lat))
        }
      })
    }

    return {
      map,
      marker,
      visible,
      ...toRefs(state),
      submit,
      getMarker,
      getSourceData,
      getLevelData,
      getBusinessData,
      areaChange,
      channelChange
    }
  }
}
</script>

<style scoped lang="scss">
#map {
  width: 89.8%;
  height: 150px;
  margin-top: 10px;
}
</style>
